package com.cg.managesystem.controller;

import com.cg.managesystem.common.JSONResult;
import com.cg.managesystem.entity.*;
import com.cg.managesystem.service.LoginTicketService;
import com.cg.managesystem.service.PostService;
import com.cg.managesystem.service.RedisHashService;
import com.cg.managesystem.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Create tao on 2019/8/13
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    UserService userService;

    @Autowired
    PostService postService;

    @Autowired
    LoginTicketService loginTicketService;


    /**
     * 用户注册
     *
     * @param username
     * @param password
     * @return
     */

    @PostMapping("/register")
    public Map<String, String> register(String username, String password, String phone) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isBlank(username)) {
            map.put("msg", "用户名不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("msg", "密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(phone)) {
            map.put("msg", "手机不能为空");
            return map;
        }
        User u = userService.selectByUserName(username);
        if (u != null) {
            map.put("msg", "用户名已经被占用");
            return map;
        }
        //前端参数没问题，开始向数据库插入数据
        User user = new User();
        user.setUsername(username);
        user.setSalt(UUID.randomUUID().toString().substring(0, 5));
//        user.setSalt("e1f2a");
        user.setPassword(DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes()));
        user.setPhone(phone);
        user.setType("0");
        user.setLevel(0);
        user.setDatetime(new Date());
        userService.insert(user);
        System.out.println("注册成功");
        map.put("msg", "注册成功");
        return map;

    }

    public Map<String, String> login(String username, String password) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isBlank(username)) {
            map.put("msg", "用户名不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("msg", "密码不能为空");
            return map;
        }
        User u = userService.selectByUserName(username);
        if (u == null) {
            map.put("msg", "用户名不存在");
            return map;
        }
        if (DigestUtils.md5DigestAsHex((password + u.getSalt()).getBytes()) == (u.getPassword())) {
            map.put("msg", "密码错误");
            return map;
        }
        String ticket = addLoginTicket(u.getUid());
        map.put("ticket", ticket);

        return map;
    }

    /**
     * 登录
     *
     * @param
     * @param httpResponse
     * @param username
     * @param password
     * @param
     * @return
     */

    @PostMapping("/login")
    public JSONResult login(HttpServletResponse httpResponse,
                            @RequestParam String username,
                            @RequestParam String password) {
        Map<String, String> map = login(username, password);
        //判断Map里是否有ticket
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket"));
            cookie.setPath("/");
            httpResponse.addCookie(cookie);
            System.out.println("登录成功");
            return JSONResult.ok();
        } else {
            System.out.println("登录失败");
            return JSONResult.errorMsg("login");
        }
    }


    /**
     * 向数据库插入Ticket
     *
     * @param userId
     * @return
     */
    public String addLoginTicket(int userId) {
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUid(userId);
        Date date = new Date();
        //过期时间
        date.setTime(date.getTime() + 1000 * 3600 * 30);
        loginTicket.setExpired(date);
        loginTicket.setStatus(0);
        loginTicket.setTicket(UUID.randomUUID().toString().replaceAll("-", ""));
        Date expired = loginTicket.getExpired();
        String ticket = loginTicket.getTicket();
        int id = userId;
        if (loginTicketService.isLoginTicket(userId)) {
            loginTicketService.updateLoginTicket(expired, ticket, id);
            System.out.println("更新ticket成功");
        } else {
            loginTicketService.addLoginTicket(loginTicket);
            System.out.println("生成Ticket成功");
        }

        return loginTicket.getTicket();
    }

    public JSONResult createRepairOrder(Repair repair) {
        return JSONResult.ok();
    }

    /**
     * 新发帖子，需传入两个参数用户Id和帖子内容
     *
     * @param post
     * @param uid
     * @param text
     * @return JSONResult
     */
    @PostMapping(value = "/addPost")
    public JSONResult addPost(Post post,
                              @RequestParam Integer uid,
                              @RequestParam String text) {
        post.setUid(uid);
        post.setText(text);
        post.setDatetime(new Date());
        int result = postService.addPost(post);
        if (result != 0) {
            return JSONResult.ok("发帖成功");
        } else {
            return JSONResult.errorMsg("发帖失败");
        }
    }


}
